package cn.jobstart.web.common;

import cn.jobstart.common.StringUtil;
import cn.jobstart.common.redis.RedisUtil;
import com.alibaba.fastjson.JSONObject;

import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Yuan.x.i.n@foxmail.com
 *
 * @author Yuan.x.i.n@foxmail.com
 * @Date 2019-12-09 09:56
 * @description
 */
@Component
public class SourceUtil extends RedisUtil {
    private static final String YYRC_SOURCE_INFO = "yyrc_source_info";

    private static SourceUtil sourceUtil = new SourceUtil();


    public static SourceUtil getInstance() {

        return sourceUtil;
    }

    public JSONObject getSource(String url) throws Exception {
        JSONObject jsonObject;
        List<Object> objects = lGet(YYRC_SOURCE_INFO);
        if (StringUtil.isObjEmpty(objects)) {
            throw new Exception("分站数据不存在");
        }
        for (Object object : objects) {
            jsonObject = JSONObject.parseObject(String.valueOf(object));
            if (url.equalsIgnoreCase(jsonObject.getString("url"))) {
                return jsonObject;
            }
        }
        throw new Exception("分站数据不存在");
    }


    public String getId(String url) throws Exception {
        return getSource(url).getString("id");
    }

    /**
     * 根据url
     *
     * @param url
     * @return
     */
    public int getSourceFlag(String url) {

        if(StringUtil.isNullOrEmpty(url)) {
            return 0;
        }

        try {
            return getSource(url).getIntValue("source");
        } catch (Exception e) {
           // e.printStackTrace();
        }
        return 0;

    }

    /**
     * 传入来源对象json
     *
     * @param json
     */
    public void setSource(String json) {
        lSet(YYRC_SOURCE_INFO, json);
    }


    /**
     * 根据id 删除对应分站数据
     *
     * @param id
     * @return
     */
    public void delete(String id) {
        JSONObject jsonObject;
        List<Object> objects = lGet(YYRC_SOURCE_INFO);
        if (StringUtil.isNotObjEmpty(objects)) {
            for (Object object : objects) {
                jsonObject = JSONObject.parseObject(String.valueOf(object));
                if (id.equalsIgnoreCase(jsonObject.getString("id"))) {
                    lRemove(YYRC_SOURCE_INFO, 1, object);
                }
            }
        }
    }

    /**
     * 清除整个key
     */
    public void resetAllSource(List<String> jsons) {
        del(YYRC_SOURCE_INFO);
        for (String json : jsons) {
            lSet(YYRC_SOURCE_INFO, json);
        }
    }

    /**
     * 根据json值 更新redis中list的元素对象
     *
     * @param json
     */
    public void update(String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        delete(jsonObject.getString("id"));
        setSource(json);
    }
}
